#!/usr/bin/env python

"""
Convert Astropy.table (*.cat or *.tab) into Excel file.
"""

import os, sys
from astropy.table import Table
import xlsxwriter as xw

def Tab2Excel(data, ExcelFileName):
    """
    Write data extracted from a astropy.Table into a Excel file.
    """
    workbook = xw.Workbook(ExcelFileName,{'nan_inf_to_errors': True})
    worksheet1 = workbook.add_worksheet("sheet1")
    worksheet1.activate()

    i = 1
    for j in range(len(data)):
        row_data = data[j]
        row = 'A' + str(i)
        worksheet1.write_row(row, row_data)
        i += 1

    workbook.close()


def Tab2Data(tabFileName, format='ipac'):
    """
    Extract header and data from a astropy.table
    """
    tab = Table.read(tabFileName, format=format)

    tabdata = []
    tabdata.append(tab.keys())
    
    colnames = tab.colnames

    if tabFileName.find('ptc') >= 0:
        if 'wave' in tab.items():
            waves = list(dict.fromkeys(tab['wave']))
            for i in range(len(waves)):
                if waves[i] < 2000:
                    for j in range(1,17):
                        print('wave: {}, ch: {}'.format(waves[i], j))
                        for k in range(len(tab)):
                            if tab[k]['wave'] == waves[i] and tab[k]['channel'] == j:
                                tabdata.append(tab[k].as_void())
            return tabdata

    for i in range(len(tab)):
        tabdata.append(tab[i].as_void())
    
    return tabdata

def runTest():
    """
    Perform a test.
    """
    testData = [
                [1, "A", 100],
                [2, "B", 200],
                [3, "C", 300]
            ]

    Tab2Excel(testData, "test.xlsx")

def main():
    tabFileName = sys.argv[1]
    tabExcelName= None
    if tabFileName.find('.cat') > 0:
        tabExcelName = tabFileName[0:tabFileName.find('.cat')] + '.xlsx'
    if tabFileName.find('.tab') > 0:
        tabExcelName = tabFileName[0:tabFileName.find('.tab')] + '.xlsx'

    tabdata = Tab2Data(tabFileName)
    Tab2Excel(tabdata, tabExcelName)
    print('--> finished converting {} to {}'.format(tabFileName, tabExcelName))



if __name__ == '__main__':
    #runTest()
    main()
